﻿
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LitJson;
using UnityEngine;

public class ShipUIManager
{
    public static ShipUIManager Instance = new ShipUIManager();
    List<ShipUIObjectBase> m_ShipUIObjs = new List<ShipUIObjectBase>();

    private ShipUIManager()
    {
    }


    public ShipUIData Create(JsonData root)
    {
        ShipUIData newShipUIData = null;
        IDictionary<string, JsonData> rootObj = root.ValueAsObject();
        if (rootObj.ContainsKey("ShipUIType"))
        {
            var type = (ShipUI.ShipUIType)rootObj["ShipUIType"].ValueAsInt();
            newShipUIData = Create((int)type);
            if (newShipUIData != null)
            {
                newShipUIData.Load(root);
            }
        }
        return newShipUIData;
    }

    public void Load()
    {
        ShipUI.InitShipUIPrefabs();
        register<ShipUIButtonData>(ShipUI.ShipUIType.Button);
        register<ShipUIMovePoleData>(ShipUI.ShipUIType.MovePole);
        register<ShipUIShipInfoData>(ShipUI.ShipUIType.ShipInfo);
    }

    public void register<T>(ShipUI.ShipUIType type) where T : new()
    { 
        var shpUIObj = new ShipUIObject<T>();
        shpUIObj.m_TypeID = type;
        shpUIObj.m_Name = type.ToString();
        m_ShipUIObjs.Add(shpUIObj);
    }

    public ShipUIData Create(string itemName)
    {
        for (int i = 0; i < m_ShipUIObjs.Count; ++i)
        {
            if (m_ShipUIObjs[i].m_Name == itemName)
            {
                return m_ShipUIObjs[i].create();
            }
        }
        return null;
    }
    public ShipUIData Create(int typeID)
    {
        for (int i = 0; i < m_ShipUIObjs.Count; ++i)
        {
            if ((int)m_ShipUIObjs[i].m_TypeID == typeID)
            {
                var newItem = Create(m_ShipUIObjs[i].m_TypeID.ToString());
                return newItem;
            }
        }
        return null;
    }


}

public class ShipUIObjectBase
{
    public ShipUI.ShipUIType m_TypeID;
    public string m_Name;
    virtual public ShipUIData create()
    {
        return null;
    }
}

public class ShipUIObject<T> : ShipUIObjectBase where T : new()
{
    public ShipUIObject()
    {
    }
    public override ShipUIData create()
    {
        var theNewOne = new T() as ShipUIData;
        theNewOne.m_Type = m_TypeID;
        return theNewOne;
    }
}